package com.yinhai.message.manage.register.bpo;

import com.yinhai.core.common.api.base.IPage;
import com.yinhai.core.common.api.util.StringUtil;
import com.yinhai.core.common.ta3.dto.TaParamDto;
import com.yinhai.message.api.bean.TMMessage;
import com.yinhai.message.api.bean.TMUser;
import com.yinhai.message.implement.app.util.PushContontrol;
import com.yinhai.message.manage.register.dao.IAppConfigDao;
import com.yinhai.message.manage.register.po.AppConfigPo;
import com.yinhai.message.manage.register.vo.AppConfigVo;

import java.util.List;

/**
*
*@author lanyc
*@version created: 2017年4月5日上午10:23:27
*/
public class AppConfigBpoImpl implements IAppConfigBpo {
	private IAppConfigDao appConfigDao;
	
	public IAppConfigDao getAppConfigDao() {
		return appConfigDao;
	}

	public void setAppConfigDao(IAppConfigDao appConfigDao) {
		this.appConfigDao = appConfigDao;
	}

	@Override
	public List<AppConfigVo> queryAllAppConfig() {
		return appConfigDao.queryAllAppConfig();
	}

	@Override
	public Integer addAppConfig(AppConfigPo acp) {
		if(acp.getDefaultApp()!=null&&acp.getDefaultApp()==1){
			removeDefault();
		}
		appConfigDao.addAppConfig(acp);
		return null;
	}

	@Override
	public Integer updateAppConfig(AppConfigPo acp) {
		if(acp.getDefaultApp()!=null&&acp.getDefaultApp()==1){
			removeDefault();
		}
		appConfigDao.updateAppConfig(acp);
		return null;
	}

	@Override
	public Integer deleteAppConfig(String appKey) {
		appConfigDao.deleteAppConfig(appKey);
		return null;
	}

	@Override
	public AppConfigVo queryDefaultAppConfig() {
		return appConfigDao.queryDefaultAppConfig();
	}

	@Override
	public AppConfigVo queryAppCfgByAppKey(String appKey) {
		return appConfigDao.queryAppCfgByAppKey(appKey);
	}

	@Override
	public void removeDefault() {
		appConfigDao.removeDefault();
	}

	@Override
	public AppConfigVo queryAppBySystemId(String systemId) {
		if(systemId==null){
			return null;
		}
		List<AppConfigVo> acvs = appConfigDao.queryAllAppConfig();
		for (AppConfigVo acv : acvs) {
			String sysIds = acv.getSystemId();
			if(StringUtil.isNotEmpty(sysIds)){
				String[] ids = sysIds.trim().split(",");
				for (int i = 0; i < ids.length; i++) {
					if(systemId.equals(ids[i])){
						return acv;
					}
				}
			}
		}
		return null;
	}

	@Override
	public void validateAppConfig(String appKey, String masterSecret,String regIdForTest) {
		TMUser user = new TMUser();
		TMMessage message = new TMMessage();
		message.setTitle("通知消息");
		message.setContent("来自ta3平台的测试推送消息!");
		user.setRegistrationId(regIdForTest);
		try {
			PushContontrol.pushMessage(user,message,masterSecret,appKey);
		} catch (cn.jpush.api.common.resp.APIConnectionException e) {
			e.printStackTrace();
		} catch (cn.jpush.api.common.resp.APIRequestException e) {
			e.printStackTrace();
		}
	}

	@Override
	public IPage queryAllAppConfigByPage(TaParamDto dto, int start, int limit, String string) {
		return appConfigDao.queryAllAppConfigByPage(dto,start,limit,string);
	}

}
